package org.maxgroundstation.simulation.service;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Contains the header and data for a service data fragment to be sent 
 * or which has been received.
 */
public class ServiceDataFragment {

	// Data members.
	private ServiceDataFragmentHeader header;
	private byte[] data;
	
	/**
	 * Constructor.
	 */
	public ServiceDataFragment() {
		header = new ServiceDataFragmentHeader();
		data = new byte[0];
	}
	
	/**
	 * Gets the fragment header.
	 * @return header.
	 */
	public ServiceDataFragmentHeader getHeader() {
		return header;
	}
	
	/**
	 * Sets the fragment header.
	 * @param header the new header.
	 */
	public void setHeader(ServiceDataFragmentHeader header) {
		this.header = header;
	}
	
	/**
	 * Gets the fragment data.
	 * @return data.
	 */
	public byte[] getData() {
		return data;
	}
	
	/**
	 * Sets the fragment data.
	 */
	public void setData(byte[] data) {
		this.data = data;
	}
	
	/**
	 * Gets the packet data for the fragment.
	 * @return the packet data.
	 */
	public byte[] toPacketData() {
		ByteBuffer buff = ByteBuffer.allocate(data.length + 40);
		buff.order(ByteOrder.LITTLE_ENDIAN);
		
		buff.putLong(header.getSyncHeader());
		buff.put(header.getServiceID().getBytes());
		buff.put(header.getClientID().getBytes());
		buff.putInt((int) header.getFrameLength());
		buff.putShort((short) header.getFragSize());
		buff.putShort((short) header.getFragNumber());
		buff.putLong(header.getTimestamp());
		buff.put(data);
		
		return buff.array();
	}
}